package dialog

import (
	"context"

	"paper-pro/app/chat/api/internal/svc"
	"paper-pro/app/chat/api/internal/types"
	"paper-pro/pkg/ctxdata"
	"paper-pro/pkg/rpc/chat/client/chatdialogservice"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type RenameLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// rename chat dialog
func NewRenameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RenameLogic {
	return &RenameLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RenameLogic) Rename(req *types.ChatDialog) (resp *types.ChatDialog, err error) {
	userId, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(err, "Chat Dialogs Rename: get UserId error: %v", err)
	}

	rpcResp, err := l.svcCtx.ChatDialogRpc.Update(l.ctx, &chatdialogservice.ChatDialogUpdateReq{
		Dialog: &chatdialogservice.ChatDialog{
			Id:        req.Id,
			Name:      req.Name,
			UserId:    userId,
			RequestId: req.RequestId,
		},
	})
	if err != nil {
		return nil, errors.Wrapf(err, "Chat Dialogs Rename: ChatDialogRpc Update error: %v", err)
	}

	resp = &types.ChatDialog{}
	copier.Copy(resp, rpcResp.Dialog)

	return
}
